package com.bridgetree.jubaocrm.ui;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.JsonObjectPostRequest;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.project.XMChildActivity;
import com.bridgetree.jubaocrm.util.Announcement;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.Projects;

/**
 * 我的公告
 */
public class MyAnnouncementActivity extends Activity {
	private Context mContext;
	private final String tag = "MyAnnouncementActivity";
	private String ggid;
	private String title;
	private TextView data_tv;
	private TextView TextView01;
	private Button chuli;
	private Button Button01;
	private SharedPreferences prefs;
	private String user_id = "";
	private String token = "";
	private Announcement mAnnouncement;
	private int Pageindex = -1;
	private boolean isDone = false;
	private String progest = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.company_nnouncement);
		mContext = this;

		Intent intent = getIntent();
		if (intent == null) {
			Log.e(tag, "intent is null");
			return;
		}

		progest = "";
		isDone = false;
		prefs = PreferenceManager
				.getDefaultSharedPreferences(MyAnnouncementActivity.this);

		TextView xm_sp_tv_title = (TextView) findViewById(R.id.xm_sp_tv_title);
		data_tv = (TextView) findViewById(R.id.data_tv);
		TextView01 = (TextView) findViewById(R.id.TextView01);
		chuli = (Button) findViewById(R.id.chuli);
		Button01 = (Button) findViewById(R.id.Button01);

		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, "");
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");
		mAnnouncement = (Announcement) intent.getExtras().getSerializable(
				"mAnnouncement");

		ggid = intent.getExtras().getString("ggid");
		title = intent.getExtras().getString("title");
		Pageindex = intent.getExtras().getInt("index");
		boolean is_done = mAnnouncement.getIs_done();
		data_tv.setText(mAnnouncement.getExpire_date());
		String text = mAnnouncement.getContent();
		int sss = text.indexOf("点击");
		if(sss<0){
			Button01.setVisibility(View.GONE);
			TextView01.setText(text);
		}else{
			TextView01.setText(text.substring(0, sss));

			int start = text.indexOf("?pid=");
			int end = text.indexOf("'>这里");
			progest = text.substring(start + 5, end);	
		}

		xm_sp_tv_title.setText(mAnnouncement.getTitle());

		findViewById(R.id.xm_sp_RelativeLayout_back).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						if (isDone) {
							Intent intent = new Intent();
							intent.putExtra("index", Pageindex);
							setResult(0x0004, intent);
						}
						finish();
					}
				});

		Button01.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!progest.equals("")) {
					getBasicInfomation(progest);
				}
			}
		});

		if (is_done) {
			chuli.setText("已处理");
			chuli.setTextColor(Color.BLACK);
			chuli.setBackgroundResource(R.drawable.login_deng);
			chuli.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
				}
			});
			isDone = true;
		} else {
			chuli.setText("处理");
			chuli.setTextColor(Color.WHITE);
			chuli.setBackgroundResource(R.drawable.login_blue);
			chuli.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					getChuLi();
				}
			});
		}
	}

	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title).setMessage(content)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						if (content != null && content.trim().equals("用户不存在")) {
							// finish();
						}
						if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
							LoginUtil.executeLoginFaild(mContext);
						}
						if("处理成功！".equals(content)){
							Intent intent = new Intent();
							intent.putExtra("index", Pageindex);
							setResult(0x0004, intent);
							finish();
						}

					}
				}).show();
	}

	// private void openDailog(String title, String content) {
	// new AlertDialog.Builder(mContext).setTitle(title)
	// .setMessage(content).setPositiveButton("确定", new
	// DialogInterface.OnClickListener() {
	//
	// @Override
	// public void onClick(DialogInterface dialog, int which) {
	// // TODO Auto-generated method stub
	//
	// }
	// }).show();
	// }

	private void getChuLi() {
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else {
			final ProgressDialog progressDialog=ProgressDialogUtil.show(mContext);
			// fid=53731b5fd5ac700a008e3f47
			// &user_id=3a2ca74f8b484303ade9b7e2655994d9
			// &token=e5c13d5937de4de49fd42735e342d99b
			// &validation=gAJ9cQAoVQZsb2NhbGVxAVUFemhfQ05xAl

			HashMap<String, String> mMap = new HashMap<String, String>();
			mMap.put("fid", mAnnouncement.getId());
			mMap.put("user_id", user_id);
			mMap.put("token", token);
			mMap.put("validation", CRMUserBaseInfo.kValication);
			String URL = Network.API_DOMAIN + "/info/done";

			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectPostRequest jsonObjectPostRequest = new JsonObjectPostRequest(
					URL, new Response.Listener<JSONObject>() {

						@Override
						public void onResponse(JSONObject response) {
							ProgressDialogUtil.dissmis(progressDialog);
							try {
								System.out.println("处理  response=" + response);
								if (!response.isNull("errors")) {
									String errors = response.get("errors")
											.toString();
									if (errors.equals("[]")) {
										openDailog("网络提示", "处理成功！");
										chuli.setText("已处理");
										chuli.setTextColor(Color.BLACK);
										chuli.setBackgroundResource(R.drawable.login_deng);
										isDone = true;
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response
													.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr
														.length(); i++) {
													JSONObject jsonObj2 = jsonArr
															.getJSONObject(i);
													if (!jsonObj2
															.isNull("desc")) {
														String desc = jsonObj2
																.getString("desc");
														openDailog("失败提示", desc);
														mLoginError
																.setDesc(desc);
													}
													if (!jsonObj2
															.isNull("value")) {
														String value = jsonObj2
																.getString("value");
														mLoginError
																.setValue(value);
													}
												}
											}
										}
									}
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							ProgressDialogUtil.dissmis(progressDialog);
							Toast.makeText(mContext, "网络未连接！",
									Toast.LENGTH_LONG).show();
						}
					}, mMap);
			requestQueue.add(jsonObjectPostRequest);
		}

	}

	/**
	 * 获取基本信息
	 */
	private void getBasicInfomation(String mProjects) {
		System.out.println("项目   =   " + mProjects);
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else {
			String URL = Network.API_DOMAIN
					+ "/base_info_of_project?project_id=" + mProjects
					+ "&user_id=" + user_id + "&token=" + token
					+ "&validation=" + CRMUserBaseInfo.kValication;
			final ProgressDialog progressDialog = ProgressDialog.show(mContext,
					"网络数据", "...Loading...");
			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
					Request.Method.GET, URL, null,
					new Response.Listener<JSONObject>() {
						@Override
						public void onResponse(JSONObject response) {
							Log.d("JSONObject", "response:" + response);
							try {
								// System.out.println("response="+response);
								if (progressDialog.isShowing()
										&& progressDialog != null) {
									progressDialog.dismiss();
								}
								if (response.isNull("errors")
										|| response.get("errors").toString()
												.equals("[]")) {
									Projects mProjects = new Projects();
									if (!response.isNull("is_approved")) {
										boolean is_approved = Boolean.valueOf(response
												.getString("is_approved"));
										mProjects.setIs_approved(is_approved);
									}
									if (!response.isNull("client_id")) {
										String client_id = response
												.getString("client_id");
										mProjects.setClient_id(client_id);
									}
									if (!response.isNull("project_name")) {
										String project_name = response
												.getString("project_name");
										mProjects.setProject_name(project_name);
									}
									if (!response.isNull("project_id")) {
										String project_id = response
												.getString("project_id");
										mProjects.setProject_id(project_id);
									}
									if (!response.isNull("process_status")) {
										String project_status = response
												.getString("process_status");
										mProjects
												.setProcess_status(project_status);
									}

									if (!response
											.isNull("is_user_in_this_project")) {
										String is_user_in_this_project = response
												.getString("is_user_in_this_project");
										mProjects
												.setIs_user_in_this_project(Boolean
														.parseBoolean(is_user_in_this_project));
									}
									if (!response.isNull("is_final_approve")) {
										String is_final_approve = response
												.getString("is_final_approve");
										mProjects.setIs_final_approve(Boolean
												.parseBoolean(is_final_approve));
									}
									if (!response.isNull("is_approve_project")) {
										String is_approve_project = response
												.getString("is_approve_project");
										mProjects.setIs_approve_project(Boolean
												.parseBoolean(is_approve_project));

									}
									if (!response.isNull("is_creater")) {
										String is_creater = response
												.getString("is_creater");
										mProjects.setIs_creater(Boolean
												.parseBoolean(is_creater));
									}
									if (!response
											.isNull("flag_only_view_base_info")) {
										String flag_only_view_base_info = response
												.getString("flag_only_view_base_info");
										mProjects
												.setFlag_only_view_base_info(Boolean
														.parseBoolean(flag_only_view_base_info));
									}
									if (!response.isNull("is_edit_project")) {
										String is_edit_project = response
												.getString("is_edit_project");
										mProjects.setIs_edit_project(Boolean
												.parseBoolean(is_edit_project));
									}
									if (!response.isNull("approved_date")) {
										String approved_date = response
												.getString("approved_date");
										mProjects
												.setApproved_date(approved_date);
									}
									if (!response.isNull("approved_by")) {
										String approved_by = response
												.getString("approved_by");
										mProjects.setApproved_by(approved_by);
									}
									if (!response.isNull("approved_by")) {
										String approved_by = response
												.getString("approved_by");
										mProjects.setApproved_by(approved_by);
									}
									if (!response.isNull("is_view_all_projects_or_reviewers")) {
										String is_view_all_projects_or_reviewers = response
												.getString("is_view_all_projects_or_reviewers");
										mProjects.setIs_view_all_projects_or_reviewers(Boolean
														.parseBoolean(is_view_all_projects_or_reviewers));
									}
									
									mProjects.setUser_id(user_id);
									mProjects.setToken(token);
									Intent intent = new Intent(mContext,
											XMChildActivity.class);
									Bundle bundle = new Bundle();
									bundle.putSerializable("my_projects",
											mProjects);
									intent.putExtras(bundle);
									((Activity) mContext).startActivity(intent);
								} else {
									String errors = response.get("errors")
											.toString();
									if (errors.equals("[]")) {
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response
													.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr
														.length(); i++) {
													JSONObject jsonObj2 = jsonArr
															.getJSONObject(i);
													if (!jsonObj2
															.isNull("desc")) {
														String desc = jsonObj2
																.getString("desc");
														openDailog("失败提示", desc);
														mLoginError
																.setDesc(desc);
													}
													if (!jsonObj2
															.isNull("value")) {
														String value = jsonObj2
																.getString("value");
														mLoginError
																.setValue(value);
													}
												}
											}
										}
									}
								}

							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError arg0) {
							Log.d("MyAnnouncementActivity", "sorry,Error");
							openDailog("失败提示", "没有找到该项目");
							if (progressDialog.isShowing()
									&& progressDialog != null) {
								progressDialog.dismiss();
							}
						}
					});
			requestQueue.add(jsonObjectRequest);
		}
	}

}
